#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/8/27 14:39
# @File           : views
# @IDE            : PyCharm
# @desc           : 描述

from fastapi import APIRouter, Depends
from utils.response import SuccessResponse
from . import schemas, crud, params
from core.dependencies import IdList
from apps.base.auth.validate import Auth, AllUserAuth
from apps.dispatch.taskpool.crud import TaskPoolDal
from apps.dispatch.taskpool.schemas import TaskNeed
from apps.dispatch.taskpool.models import DCTask
from sqlalchemy.orm import joinedload


app = APIRouter()


###################################################
#   需求计划管理                                     #
###################################################
@app.get("/need/plan", summary="获取辅料计划")
async def get_need_plan(
        p: params.NeedPlanParams = Depends(),
        auth: Auth = Depends(AllUserAuth())
):
    datas, count = await crud.NeedPlanDal(auth.db).get_datas(
        **p.dict(),
        v_schema=schemas.NeedPlanOut,
        v_return_count=True
    )
    return SuccessResponse(datas, count=count)


@app.post("/need/plan", summary="创建计划")
async def create_need_plan(
        data: schemas.NeedPlan,
        auth: Auth = Depends(AllUserAuth())
):
    data.create_user = auth.user.user_str
    return SuccessResponse(await crud.NeedPlanDal(auth.db).create_data(data))


@app.put("/need/plan/{data_id}", summary="更新计划")
async def put_need_plan(
        data_id: int,
        data: schemas.NeedPlan,
        auth: Auth = Depends(AllUserAuth())

):
    data.update_user = auth.user.user_str
    return SuccessResponse(await crud.NeedPlanDal(auth.db).put_data(data_id, data=data))


@app.delete("/need/plan", summary="批量删除计划", description="软删除")
async def delete_feedback(ids: IdList = Depends(), auth: Auth = Depends(AllUserAuth())):
    await crud.NeedPlanDal(auth.db).delete_datas(ids=ids.ids)
    return SuccessResponse("删除成功")


@app.put("/need/plan/{data_id}/trigger", summary="辅料需求下发至物料组件", description="状态更改至'已下发'")
async def trigger_need_plan(
        data_id: int,
        data: schemas.NeedPlanTrigger,
        auth: Auth = Depends(AllUserAuth())
):
    if data.method == 'drop':
        await crud.NeedPlanDal(auth.db).drop_plan(data_id)
        return SuccessResponse("更新成功")
    elif data.method == 'call':
        await crud.NeedPlanDal(auth.db).call_plan(data_id)
        return SuccessResponse("更新成功")


@app.get("/need", summary="识别辅料需求", description="按工位识别")
async def recognize_needs(
    p: params.RecogizeNeedParams = Depends(),
    auth: Auth = Depends(AllUserAuth())
):
    data = {}
    tasks = await TaskPoolDal(auth.db).get_datas(
        **p.dict(),
        v_options=[joinedload(DCTask.needs)],
        v_return_objs=True
    )
    for task in tasks:
        for need in task.needs:
            key = str(need.type) + '|' + str(need.name) + '|' + str(need.unit).lower()
            if key not in data:
                data[key] = {
                    'type': need.type,
                    'name': need.name,
                    'unit': need.unit.lower() if need.unit else '',
                    'number': 0,
                    'remark': ''
                }
            data[key]['number'] += float(need.number) if need.number and need.number.isdigit else 0
            data[key]['remark'] += f"{task.ticket_id}({task.ao_id})\n"

    return SuccessResponse(list(data.values()))
